package cn.xiaopengstack.domain.activity.service.quota.rule.chain;

import cn.xiaopengstack.domain.activity.model.entity.ActionRuleMatterEntity;
import cn.xiaopengstack.domain.activity.model.entity.RaffleActivityEntity;
import cn.xiaopengstack.domain.activity.model.valobj.ActivityStateVO;
import cn.xiaopengstack.domain.activity.service.quota.rule.factory.DefaultActivityActionChainFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @author jiangyangang
 * 有效性检查
 * -时间
 * -状态
 */
@Component
@Slf4j
public class ValidityActionChain extends AbstractActionChain {

    @Override
    public DefaultActivityActionChainFactory.ActionEnum action() {
        return DefaultActivityActionChainFactory.ActionEnum.VALIDITY_CHECK_ACTION;
    }

    @Override
    public boolean doChain(ActionRuleMatterEntity ruleMatter) {
        RaffleActivityEntity activity = ruleMatter.getActivity();
        // 是否过期了
        long endDateTime = activity.getEndDateTime().toInstant().toEpochMilli();
        long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (now >= endDateTime) {
            log.warn("活动责任链，活动已经过期了; {}, {}", activity.getActivityId(), endDateTime);
            return false;
        }

        long beginTime = activity.getBeginDateTime().toInstant().toEpochMilli();
        if (now < beginTime) {
            log.warn("活动责任链，活动还未开始; {}, {}", activity.getActivityId(), beginTime);
            return false;
        }

        // 状态是否失效
        ActivityStateVO state = activity.getState();
        if (ActivityStateVO.close.equals(state) || ActivityStateVO.create.equals(state)) {
            log.warn("活动责任链，无效的活动状态。{}, {}", activity.getActivityId(), state);
            return false;
        }
        log.info("活动责任链，活动状态检查通过。{}, {}", activity.getActivityId(), state);
        return next().doChain(ruleMatter);
    }

    @Override
    public int getOrder() {
        return action().getOrder();
    }
}
